package com.qinglei.recoup.app.controller;

import com.qinglei.recoup.app.pojo.WxLoginInfo;
import com.qinglei.recoup.common.domain.CommonRes;
import com.qinglei.recoup.common.exception.RecoupException;
import com.qinglei.recoup.common.properties.WxProperties;
import com.qinglei.recoup.common.utils.RecoupUtil;
import com.qinglei.recoup.system.domain.User;
import com.qinglei.recoup.system.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/weixin")
public class AppLoginController {

    @Autowired
    private LoginService loginService;

    /**
     * 微信登录
     * @param wxLoginInfo
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/loginByWeixin")
    public CommonRes loginByWeixin(@RequestBody WxLoginInfo wxLoginInfo, HttpServletRequest request) throws Exception {
        String openId = UUID.randomUUID().toString();
        CommonRes loginRes = loginService.appLogin(wxLoginInfo);
        log.info("login result: {}", loginRes);
        return loginRes;
    }

    /**
     * 微信小程序退出
     * @return
     * @throws Exception
     */
    @PostMapping("/logoutByWeixin")
    public CommonRes logoutByWeixin() throws Exception {
        try {
            User currentUser = RecoupUtil.getCurrentUser();
            String token = RecoupUtil.getCurrentToken();
            Long userId = currentUser.getId();
            loginService.logout(userId, token, currentUser.getTenantId());
            return CommonRes.ok("退出系统成功");
        } catch (Exception e) {
            String message = "退出系统失败";
            log.error(message, e);
            throw new RecoupException(message);
        }
    }



}
